<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\City;
use App\Models\Fang;
use App\Models\FangAttrs;
use App\Models\FangOwner;

use App\severces\EsSeverce;
use App\severces\GaodeSeverce;
use Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;

class FangController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //接收搜索内容
        $keyword = $request->get('keyword');

        if(!empty($keyword)){
            //实例化es类
            $esObj = new EsSeverce();
            //调用es搜索方法
            $data = $esObj->esSearch('fang',$keyword);

            $fang = $data['hits']['hits'];

            return view('admin.fang.index',compact('fang'));

        }

        $fang = Fang::paginate($this->paginate);

        return view('admin/fang/index',compact('fang'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //省
        $cityData = City::getCityIdbypid(0);
        //房东信息
        $fangowner = FangOwner::select('id','name')->get();
        //租期方式
        $getfangRentTypeId = FangAttrs::where('filed_name','fang_rent_type')->value('id');
        $fangRentType = FangAttrs::where('pid',$getfangRentTypeId)->select('id','name')->get();
        //租赁方式
        $getFangRentClassId = FangAttrs::where('filed_name','fang_rent_class')->value('id');
        $fangRentClass = FangAttrs::where('pid',$getFangRentClassId)->select('id','name')->get();
        //房源朝向方式
        $getFangDirectionId = FangAttrs::where('filed_name','fang_direction')->value('id');
        $fangDirection = FangAttrs::where('pid',$getFangDirectionId)->select('id','name')->get();
        //配套设施
        $getfFangConfigId = FangAttrs::where('filed_name','fang_config')->value('id');
        $fangConfig = FangAttrs::where('pid',$getfFangConfigId)->select('id','name')->get();
        return view('admin/fang/create',compact('cityData','fangConfig','fangowner','fangDirection','fangRentClass','fangRentType'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $params = $request->except(['_token','file']);

        //获取省市区地址
        $fangProvince = City::getCityName($params['fang_province']);
        $fangCity = City::getCityName($params['fang_city']);
        $fangRegion = City::getCityName($params['fang_region']);
        $address = $fangProvince . $fangCity . $fangRegion .$params['fang_addr'];
        //给经纬度赋值
        list($params['longitude'],$params['latitude']) = GaodeSeverce::getLongGto($address);

        $params['fang_config'] = implode(',',$params['fang_config']);

        //向数据库中添加数据
        $res = Fang::create($params);
        //写入索引
/*
        $host = config('es.host');
        //链接es
        $client = ClientBuilder::create()->setHosts($host)->build();
        $data = [
            'index' => 'fang',
            'id'=>$res->id,
            'body' => $res->toarray(),
        ];
        $client->index($data);
*/

        if($res){
            return  redirect(route('admin.fang.index'));
        }else{
            return redirect(route('admin.fang.create'))->withErrors('添加失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * 房东图片上传
     * @param Request $request
     */
    public function localfile(Request $request)
    {
        try {
            $fileName = $request->file('file')->store('', 'fang');

            $filePath = '/uploads/fang/' . $fileName;

            return $this->witeJson(0, ['pic' => $filePath], '添加成功');
        } catch (\Exception $e) {
            return $this->witeJson(10001, null, "添加失败");
        }

    }

    /**
     * 删除本地图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delpic(Request $request)
    {
        $picPhth = $request->get('pic');
        $res = unlink(public_path() . $picPhth);

        if ($res) {
            return $this->witeJson(0, null, '删除成功');
        } else {
            return $this->witeJson(10002, null, '删除失败');

        }

    }

    /**
     * 改变房源状态
     */
    public function statusChange(Request $request)
    {
        $id = $request->all('id');

        $data = Fang::find($id);

        if($data[0]['fang_status'] == 0){
            $res = Fang::where('id',$id)->update(['fang_status'=>1]);

            if($res){
                return $this->witeJson('0',null,'修改成功');
            }else{
                return $this->witeJson('100001',null,'修改失败');
            }

        }else{
            $res = Fang::where('id',$id)->update(['fang_status'=>0]);

            if($res){
                return $this->witeJson('0',null,'修改成功');
            }else{
                return $this->witeJson('100001',null,'修改失败');
            }
    }


    }

    /**
     * 创建es索引
     */
    public function esinit()
    {
        $host = config('es.host');
        //连接es
        $client = ClientBuilder::create()
            ->setHosts($host)
            ->build();
        //创建es索引
        $params = [
            'index'=>'fang',
            'body'=>[
                'setting'=>[
                    'number_of_shards'=>5,
                    'number_od_replicas'=>1
                ],
                'mappings'=>[
                    '_source'=>[
                        'enabled'=>true
                    ],
                    'properties'=>[
                        'fang_name'=>[
                            'type'=>'text',//模糊搜索
                            'analyzer'=>'ik_max_word',//中文分词规则
                            'search_analyzer'=>'ik_max_word'//搜索使用中文分词规则
                        ]
                    ]
                ]
            ]
        ];

        $response = $client->index($params);
        dd($response);
    }
}
